package top.hiai.Controller.admin;

import java.util.Date;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

import top.hiai.interceptor.AdminInterceptor;
import top.hiai.model.Article;
import top.hiai.model.Message;
import top.hiai.service.ArcTypeService;
import top.hiai.service.ArticleService;
import top.hiai.util.FormatjsonUtil;

/**
* @Author www.hiai.top
* @Email  goodsking@163.com
* @Message 更多资源尽在www.hiai.top,开发者：黄康权
* @Introduction 后台文章控制器，对文章的增删改查
*/

public class AdminArticleController extends Controller {

	ArticleService articleService = new ArticleService();
	ArcTypeService arcTypeService = new ArcTypeService();
	/**
	 * 后台的文章管理
	 */
	@Before(AdminInterceptor.class)
	public void articleListTable(){
		
    	String s_name = get("name");
    	String s_state = get("state");
        Integer page = getParaToInt("page", 1);
        Integer limit = getParaToInt("limit", 10);
        Page<Article> paginate = articleService.paginateAdmin(page, limit,s_name,s_state);
        renderJson(FormatjsonUtil.layuiPage(paginate));
	}
	/**
	 * 后台修改文章是否为热门
	 */
	public void updateHotState(){
		int aid = getInt("aid");
		boolean is_hot = getBoolean("is_hot");
//		System.out.println("id是:"+aid+",hot:"+is_hot);
		boolean resuleId = getModel(Article.class).setAid(aid).setIs_hot(is_hot).update();
		if(resuleId){
			renderJson("success",true);
		}else{
			renderJson("success",false);
		}
	}
	
	/**
	 * 后台文章管理中文章删除
	 */
	public void deleteArticle(){
		articleService.deleteById(getParaToInt());
		redirect("/admin/adminArticleManage");
	}
	
	/**
	 * 后台编辑一个文章
	 */
	public void toModifyArticlePage(){
		Article article = articleService.findById(getParaToInt());
		int tid = article.getType_id();
		//文章的分类
		setAttr("arcTypeList", arcTypeService.findById(tid));
		//根据文章的ID获取文章的信息
		setAttr("article", article);
		setAttr("title", "修改文章资源");
    	render("/admin/adminArticleEdit.html");
	}
	/**
	 * 修改文章提交
	 */
	public void editArticle(){
		//文章资源的ID
		int aid = getParaToInt("article.aid");
		Article article = articleService.findById(aid);

		int articleUser_id = article.getUuser_id();
		//修改文章的名称
		String articleName = article.getName();
		//修改文章的状态
		int articleState = article.getState();
		//审核状态的信息
		String articleReason = get("article.reason");

		//修改返回信息的内容
		String content = "";
		//审核的的时间
		Date publish_date = new Date();
		
		if(articleState == 2){
			content = "【审核成功】 您发布的【"+articleName+"】帖子审核成功！";
		}else if(articleState == 3){
			content = "【审核失败】 您发布的【"+articleName+"】帖子审核失败！失败的原因是："+articleReason+"";
		}else{
			content = "【审核成功】 您发布的【"+articleName+"】帖子审核成功！";
		}
		
		//System.out.println("用户ID："+articleUser_id+",文章标题"+articleName+",信息内容"+content);
		getModel(Message.class).setContent(content).setPublish_date(publish_date).setUser_id(articleUser_id).save();
		
		getModel(Article.class).update();
		redirect("/admin/adminArticleManage");
	}
}
